package com.kvest.scanrecognizer.adapter;

import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.PopupMenu.OnMenuItemClickListener;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.kvest.scanrecognizer.R;
import com.kvest.scanrecognizer.datamodel.RecognizeStatus;
import com.kvest.scanrecognizer.datastorage.table.RecognizeItemTable;
import com.kvest.scanrecognizer.utility.FormatUtils;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 18.09.13
 * Time: 19:46
 * To change this template use File | Settings | File Templates.
 */
public class ConvertingListAdapter extends SimpleCursorAdapter implements SimpleCursorAdapter.ViewBinder,
                                                                          OnMenuItemClickListener,
                                                                          PopupMenu.OnDismissListener {
    private OnClickListener editNameClickListener;
    private OnClickListener downloadClickListener;
    private OnClickListener mailClickListener;
    private OnClickListener shareClickListener;
    private OnClickListener deleteClickListener;
    private OnClickListener statusClickListener;
    private OnClickListener favoriteClickListener;
    private Context context;
    private String currentUid;

    private OnActionListener onActionListener;

    public ConvertingListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to, int flags) {
        super(context, layout, cursor, from, to, flags);
        this.context = context;
        setViewBinder(this);

        //create listeners
        editNameClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onActionListener != null && v.getTag() != null) {
                    onActionListener.onEditName((Long) v.getTag());
                }
            }
        };
        downloadClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                currentUid = (String)v.getTag();
                PopupMenu popup = new PopupMenu(ConvertingListAdapter.this.context, v);
                popup.setOnMenuItemClickListener(ConvertingListAdapter.this);
                popup.setOnDismissListener(ConvertingListAdapter.this);
                popup.inflate(R.menu.format_select_popup);
                popup.show();
            }
        };
        deleteClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onActionListener != null && v.getTag() != null) {
                    onActionListener.onDelete((Long) v.getTag());
                }
            }
        };
        mailClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                currentUid = (String)v.getTag();
                showFormatSelectionForEmail(v);
            }
        };
        shareClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                currentUid = (String)v.getTag();
                showFormatSelectionForShare(v);
            }
        };
        favoriteClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onActionListener != null && v.getTag() != null) {
                    onActionListener.onFavoriteChanged((Long) v.getTag(), ((ToggleButton)v).isChecked());
                }
            }
        };
        statusClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                RecognizeStatus status = (RecognizeStatus)v.getTag();
                switch (status) {
                    case IN_PROGRESS:
                    case IN_QUEUE:
                        Toast.makeText(ConvertingListAdapter.this.context,
                                       ConvertingListAdapter.this.context.getString(R.string.status_wait),
                                       Toast.LENGTH_SHORT).show();
                        break;
                    case DONE:
                        Toast.makeText(ConvertingListAdapter.this.context,
                                       ConvertingListAdapter.this.context.getString(R.string.status_done),
                                       Toast.LENGTH_SHORT).show();
                        break;
                    case ERROR:
                        Toast.makeText(ConvertingListAdapter.this.context,
                                       ConvertingListAdapter.this.context.getString(R.string.status_error),
                                       Toast.LENGTH_SHORT).show();
                        break;
                }

            }
        };
    }

    private void showFormatSelectionForEmail(View view) {
        PopupMenu popup = new PopupMenu(ConvertingListAdapter.this.context, view);
        popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu_format_txt : onSendEmail(FormatUtils.TXT_FORMAT); return true;
                    case R.id.menu_format_doc : onSendEmail(FormatUtils.DOC_FORMAT); return true;
                    case R.id.menu_format_pdf : onSendEmail(FormatUtils.PDF_FORMAT); return true;
                    default : return false;
                }
            }
        });
        popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu popupMenu) {
                currentUid = null;
            }
        });
        popup.inflate(R.menu.format_select_popup);
        popup.show();
    }

    private void showFormatSelectionForShare(View view) {
        PopupMenu popup = new PopupMenu(ConvertingListAdapter.this.context, view);
        popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.menu_format_txt : onShare(FormatUtils.TXT_FORMAT); return true;
                    case R.id.menu_format_doc : onShare(FormatUtils.DOC_FORMAT); return true;
                    case R.id.menu_format_pdf : onShare(FormatUtils.PDF_FORMAT); return true;
                    default : return false;
                }
            }
        });
        popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu popupMenu) {
                currentUid = null;
            }
        });
        popup.inflate(R.menu.format_select_popup);
        popup.show();
    }

    @Override
    public View newView (Context context, Cursor cursor, ViewGroup parent) {
        View result = super.newView(context, cursor, parent);

        result.findViewById(R.id.name).setOnClickListener(editNameClickListener);
        result.findViewById(R.id.download).setOnClickListener(downloadClickListener);
        result.findViewById(R.id.favorite).setOnClickListener(favoriteClickListener);
        result.findViewById(R.id.mail).setOnClickListener(mailClickListener);
        result.findViewById(R.id.share).setOnClickListener(shareClickListener);
        result.findViewById(R.id.delete).setOnClickListener(deleteClickListener);
        result.findViewById(R.id.status).setOnClickListener(statusClickListener);

        return result;
    }

    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if (view.getId() == R.id.name && cursor.getColumnIndex(RecognizeItemTable._ID) == columnIndex) {
            long id = cursor.getLong(columnIndex);
            view.setTag(new Long(id));
            return true;
        }
        if (view.getId() == R.id.thumbnail) {
            byte[] data = cursor.getBlob(columnIndex);
            Bitmap thumbnail = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (thumbnail != null) {
                ((ImageView)view).setImageBitmap(thumbnail);
            }
            return true;
        }
        if (view.getId() == R.id.status) {
            RecognizeStatus status = RecognizeStatus.convert(cursor.getInt(columnIndex));
            view.setTag(status);
            switch (status) {
                case IN_PROGRESS:
                case IN_QUEUE:
                    ((ImageView)view).setImageResource(R.drawable.status_wait);
                    break;
                case DONE:
                    ((ImageView)view).setImageResource(R.drawable.status_done);
                    break;
                case ERROR:
                    ((ImageView)view).setImageResource(R.drawable.status_error);
                    break;
                default :
                    ((ImageView)view).setImageResource(R.drawable.status_wait);
            }

            return true;
        }
        if (view.getId() == R.id.download) {
            if (cursor.getColumnIndex(RecognizeItemTable.UID_COLUMN) == columnIndex) {
                String uid = cursor.getString(columnIndex);
                view.setTag(uid);
                return true;
            }
            if (cursor.getColumnIndex(RecognizeItemTable.STATUS_COLUMN) == columnIndex) {
                RecognizeStatus status = RecognizeStatus.convert(cursor.getInt(columnIndex));
                view.setEnabled(status == RecognizeStatus.DONE);
                return true;
            }
        }
        if (view.getId() == R.id.share) {
            if (cursor.getColumnIndex(RecognizeItemTable.STATUS_COLUMN) == columnIndex) {
                RecognizeStatus status = RecognizeStatus.convert(cursor.getInt(columnIndex));
                view.setEnabled(status == RecognizeStatus.DONE);
                return true;
            }
            if (cursor.getColumnIndex(RecognizeItemTable.UID_COLUMN) == columnIndex) {
                String uid = cursor.getString(columnIndex);
                view.setTag(uid);
                return true;
            }
        }
        if (view.getId() == R.id.mail) {
            if (cursor.getColumnIndex(RecognizeItemTable.STATUS_COLUMN) == columnIndex) {
                RecognizeStatus status = RecognizeStatus.convert(cursor.getInt(columnIndex));
                view.setEnabled(status == RecognizeStatus.DONE);
                return true;
            }
            if (cursor.getColumnIndex(RecognizeItemTable.UID_COLUMN) == columnIndex) {
                String uid = cursor.getString(columnIndex);
                view.setTag(uid);
                return true;
            }
        }
        if (view.getId() == R.id.delete) {
            long id = cursor.getLong(columnIndex);
            view.setTag(new Long(id));
            return true;
        }
        if (view.getId() == R.id.favorite) {
            if (cursor.getColumnIndex(RecognizeItemTable.FAVORITE_COLUMN) == columnIndex) {
                ((ToggleButton)view).setChecked(cursor.getInt(columnIndex) == 1);
                return true;
            } else if (cursor.getColumnIndex(RecognizeItemTable._ID) == columnIndex) {
                long id = cursor.getLong(columnIndex);
                view.setTag(new Long(id));
                return true;
            }
        }

        return false;
    }

    public void setOnActionListener(OnActionListener onActionListener) {
        this.onActionListener = onActionListener;
    }

    @Override
    public void onDismiss(PopupMenu popupMenu) {
        currentUid = null;
    }

    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.menu_format_txt : onFormatSelected(FormatUtils.TXT_FORMAT); return true;
            case R.id.menu_format_doc : onFormatSelected(FormatUtils.DOC_FORMAT); return true;
            case R.id.menu_format_pdf : onFormatSelected(FormatUtils.PDF_FORMAT); return true;
            default : return false;
        }
    }

    private void onShare(int format) {
        if (currentUid != null) {
            if (onActionListener != null) {
                onActionListener.onShare(currentUid, format);
            }

            currentUid = null;
        }
    }

    private void onSendEmail(int format) {
        if (currentUid != null) {
            if (onActionListener != null) {
                onActionListener.onSendEmail(currentUid, format);
            }

            currentUid = null;
        }
    }

    private void onFormatSelected(int format) {
        if (currentUid != null) {
            if (onActionListener != null) {
                onActionListener.onDownload(currentUid, format);
            }

            currentUid = null;
        }
    }

    public interface OnActionListener {
        public void onEditName(long id);
        public void onDownload(String uid, int format);
        public void onFavoriteChanged(long id, boolean value);
        public void onSendEmail(String uid, int format);
        public void onShare(String uid, int format);
        public void onDelete(long id);
    }
}
